package com.ubxtech.db.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.ubxtech.core.context.ContextUtil;
import com.ubxtech.db.properties.DbProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

/**
 * @author Victor.Xiao
 * @since 2023-10-10 17:53
 **/
@Slf4j
public class TenantEqValueHandlerImpl implements TenantLineHandler {

    private DbProperties dbProperties;

    public TenantEqValueHandlerImpl(DbProperties dbProperties){
        this.dbProperties = dbProperties;
    }
    @Override
    public Expression getTenantId() {
        String tenant = ContextUtil.getTenant();
//        if (log.isDebugEnabled()) {
//            log.debug("当前租户,{}",tenant);
//        }
        if (StrUtil.isBlank(tenant)) {
            return new StringValue("");
        }
        // 数据库的值
        return new StringValue(tenant);
    }

    @Override
    public String getTenantIdColumn() {
        // 对应数据库租户ID的列名
        return dbProperties.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {

        boolean ignoreFlag = ContextUtil.getIgnoreTenantFlag();
        if (ignoreFlag) {
            if (log.isDebugEnabled()) {
                log.debug("当前表:{},注解设置忽略租户",tableName);
            }
            return true;
        }
        ignoreFlag = dbProperties.getIgnoreTables() != null && dbProperties.getIgnoreTables().contains(tableName);
        return ignoreFlag;
    }
}
